<template>
  <div class="app-container">
    <!-- 主配置选择 -->
    <el-card class="mb-4">
      <template #header>
        <div class="card-header">
          <span>AI任务配置选择</span>
          <el-button type="primary" size="large" plain round class="ai-big-btn" style="font-weight:bold;min-width:140px;" @click="handleAddConfig">新增配置</el-button>
        </div>
      </template>
      <el-select v-model="selectedConfigId" placeholder="请选择AI任务配置" @change="handleConfigChange" style="width: 300px">
        <el-option v-for="config in configList" :key="config.id" :label="config.configName" :value="config.id">
          <span style="float: left">{{ config.configName }}</span>
          <span style="float: right; color: #8492a6; font-size: 13px">{{ config.taskType }}</span>
        </el-option>
      </el-select>
      <el-button type="text" @click="loadConfigList" style="margin-left: 10px">刷新</el-button>
    </el-card>

    <!-- 配置详情 -->
    <div v-if="selectedConfigId">
      <el-tabs v-model="activeTab">
        <!-- 基础信息 -->
        <el-tab-pane label="基础信息" name="basic">
          <el-card>
            <el-form :model="currentConfig" ref="configForm" :rules="configRules" label-width="120px">
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="配置名称" prop="configName">
                    <el-input v-model="currentConfig.configName" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="任务类型" prop="taskType">
                    <el-select v-model="currentConfig.taskType" placeholder="请选择">
                      <el-option v-for="type in taskTypes" :key="type.value" :label="type.label" :value="type.value" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-form-item label="配置描述" prop="description">
                <el-input type="textarea" v-model="currentConfig.description" :rows="3" />
              </el-form-item>
              <el-form-item label="是否启用" prop="isActive">
                <el-switch v-model="currentConfig.isActive" :active-value="1" :inactive-value="0" />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="saveConfig">保存配置</el-button>
                <el-button @click="copyConfig">复制配置</el-button>
              </el-form-item>
            </el-form>
          </el-card>
        </el-tab-pane>

        <!-- 参数配置 -->
        <el-tab-pane label="参数配置" name="params">
          <el-card>
            <template #header>
              <div class="card-header">
                <span>参数列表</span>
                <el-button type="primary" size="large" plain round class="ai-big-btn" style="font-weight:bold;min-width:140px;" @click="addParam">添加参数</el-button>
              </div>
            </template>
            
            <el-table :data="paramsList" style="width: 100%">
              <el-table-column prop="paramKey" label="参数键名" width="150">
                <template #default="scope">
                  <el-input v-if="scope.row.editing" v-model="scope.row.paramKey" size="small" placeholder="请输入参数键名" />
                  <span v-else>{{ scope.row.paramKey }}</span>
                </template>
              </el-table-column>
              
              <el-table-column prop="paramValue" label="参数值" min-width="200">
                <template #default="scope">
                  <el-input v-if="scope.row.editing" v-model="scope.row.paramValue" type="textarea" :rows="2" size="small" placeholder="请输入参数值" />
                  <div v-else class="param-value">{{ scope.row.paramValue }}</div>
                </template>
              </el-table-column>
              
              <el-table-column prop="paramType" label="参数类型" width="120">
                <template #default="scope">
                  <el-select v-if="scope.row.editing" v-model="scope.row.paramType" size="small" placeholder="请选择类型">
                    <el-option v-for="type in paramTypes" :key="type.value" :label="type.label" :value="type.value" />
                  </el-select>
                  <el-tag v-else>{{ getParamTypeText(scope.row.paramType) }}</el-tag>
                </template>
              </el-table-column>
              
              <el-table-column prop="paramDescription" label="参数描述" width="150">
                <template #default="scope">
                  <el-input v-if="scope.row.editing" v-model="scope.row.paramDescription" size="small" placeholder="请输入描述" />
                  <span v-else>{{ scope.row.paramDescription }}</span>
                </template>
              </el-table-column>
              
              <el-table-column prop="isRequired" label="必填" width="80">
                <template #default="scope">
                  <el-switch v-if="scope.row.editing" v-model="scope.row.isRequired" :active-value="1" :inactive-value="0" size="small" />
                  <el-tag v-else :type="scope.row.isRequired ? 'danger' : 'info'">{{ scope.row.isRequired ? '是' : '否' }}</el-tag>
                </template>
              </el-table-column>
              
              <el-table-column prop="sortOrder" label="排序" width="80">
                <template #default="scope">
                  <el-input-number v-if="scope.row.editing" v-model="scope.row.sortOrder" :min="0" size="small" />
                  <span v-else>{{ scope.row.sortOrder }}</span>
                </template>
              </el-table-column>
              
              <el-table-column label="操作" width="150">
                <template #default="scope">
                  <template v-if="scope.row.editing">
                    <el-button type="primary" size="small" @click="saveParam(scope.row, scope.$index)">保存</el-button>
                    <el-button size="small" @click="cancelEdit('params', scope.row, scope.$index)">取消</el-button>
                  </template>
                  <template v-else>
                    <el-button type="text" size="small" @click="editItem('params', scope.row, scope.$index)">编辑</el-button>
                    <el-button type="text" size="small" @click="deleteItem('params', scope.row, scope.$index)" class="text-red-500">删除</el-button>
                  </template>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-tab-pane>

        <!-- 提示词模板 - 修改为单个模板 -->
        <el-tab-pane label="提示词模板" name="template">
          <el-card>
            <template #header>
              <div class="card-header">
                <span>提示词模板</span>
                <div v-if="currentTemplate.editing">
                  <el-button type="primary" size="large" plain round class="ai-big-btn" style="font-weight:bold;min-width:140px;" @click="saveTemplate">保存模板</el-button>
                  <el-button size="large" plain round class="ai-big-btn" style="font-weight:bold;min-width:140px;" @click="cancelTemplateEdit">取消</el-button>
                </div>
                <div v-else>
                  <el-button type="primary" size="large" plain round class="ai-big-btn" style="font-weight:bold;min-width:140px;" @click="editTemplate" v-if="currentTemplate.id">编辑模板</el-button>
                  <el-button type="primary" size="large" plain round class="ai-big-btn" style="font-weight:bold;min-width:140px;" @click="createTemplate" v-if="!currentTemplate.editing && !currentTemplate.id">创建模板</el-button>
                </div>
              </div>
            </template>
            
            <div v-if="currentTemplate.id || currentTemplate.editing">
              <el-form :model="currentTemplate" label-width="120px">
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="模板名称">
                      <el-input v-if="currentTemplate.editing" v-model="currentTemplate.templateName" placeholder="请输入模板名称" />
                      <span v-else class="font-bold">{{ currentTemplate.templateName }}</span>
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item label="模板类型">
                      <el-select v-if="currentTemplate.editing" v-model="currentTemplate.templateType">
                        <el-option v-for="type in templateTypes" :key="type.value" :label="type.label" :value="type.value" />
                      </el-select>
                      <el-tag v-else>{{ getTemplateTypeText(currentTemplate.templateType) }}</el-tag>
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item label="使用方式">
                      <el-select v-if="currentTemplate.editing" v-model="currentTemplate.templateUsage">
                        <el-option v-for="usage in templateUsages" :key="usage.value" :label="usage.label" :value="usage.value" />
                      </el-select>
                      <el-tag type="info" v-else>{{ getTemplateUsageText(currentTemplate.templateUsage) }}</el-tag>
                    </el-form-item>
                  </el-col>
                </el-row>
                
                <el-form-item label="提示词内容">
                  <el-input v-if="currentTemplate.editing" v-model="currentTemplate.promptContent" type="textarea" :rows="12" 
                           placeholder="请输入提示词内容，可使用 {{参数名}} 来引用参数" />
                  <div v-else class="bg-gray-50 p-4 rounded whitespace-pre-wrap" style="min-height: 200px;">{{ currentTemplate.promptContent }}</div>
                </el-form-item>
                
                <el-form-item label="变量定义" v-if="currentTemplate.editing">
                  <el-input v-model="currentTemplate.variables" type="textarea" :rows="3" 
                           placeholder="JSON格式的变量定义，如：{&quot;param1&quot;: &quot;描述1&quot;, &quot;param2&quot;: &quot;描述2&quot;}" />
                </el-form-item>
                <el-form-item label="变量定义" v-else-if="currentTemplate.variables">
                  <div class="bg-gray-50 p-4 rounded">{{ currentTemplate.variables }}</div>
                </el-form-item>
              </el-form>
            </div>
            <div v-else class="text-center py-8">
              <p class="text-gray-500 mb-4">暂无模板，请创建一个新的提示词模板</p>
              <el-button type="primary" @click="createTemplate">创建模板</el-button>
            </div>
          </el-card>
        </el-tab-pane>

        <!-- 预览测试 -->
        <el-tab-pane label="预览测试" name="preview">
          <el-card>
            <template #header>
              <div class="card-header">
                <span>提示词预览</span>
                <el-button type="primary" size="large" plain round class="ai-big-btn" style="font-weight:bold;min-width:140px;" @click="previewPrompt">生成预览</el-button>
              </div>
            </template>
            
            <el-row :gutter="20">
              <el-col :span="8">
                <h4>参数值设置</h4>
                <div v-for="param in paramsList" :key="param.id" class="mb-3">
                  <el-form-item :label="param.paramKey" :required="param.isRequired">
                    <el-input v-model="previewValues[param.paramKey]" :placeholder="param.paramDescription" />
                  </el-form-item>
                </div>
              </el-col>
              <el-col :span="16">
                <h4>生成结果</h4>
                <div v-for="(content, key) in previewResult" :key="key" class="mb-4">
                  <h5>{{ key }}</h5>
                  <div class="bg-gray-50 p-4 rounded whitespace-pre-wrap">{{ content }}</div>
                </div>
              </el-col>
            </el-row>
          </el-card>
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 通用对话框 -->
    <el-dialog :title="dialogConfig.title" v-model="dialogConfig.visible" width="500px">
      <el-form :model="dialogConfig.form" :rules="configRules" ref="dialogForm" label-width="100px">
        <el-form-item v-for="field in dialogConfig.fields" :key="field.prop" :label="field.label" :prop="field.prop">
          <el-input v-if="field.component === 'el-input'" v-model="dialogConfig.form[field.prop]" v-bind="field.props" />
          <el-select v-else-if="field.component === 'el-select'" v-model="dialogConfig.form[field.prop]" v-bind="field.props">
            <el-option v-for="option in field.props.children || []" :key="option.value" :label="option.label" :value="option.value" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogConfig.visible = false">取消</el-button>
          <el-button type="primary" @click="dialogConfig.onSubmit">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { 
  getAiTaskConfigList, updateAiTaskConfig, addAiTaskConfig, getCompleteConfig,
  batchSaveConfig, copyAiConfig, removeConfigParams, removeConfigTemplates, previewConfigPrompt
} from "@/api/ai_config/ai_config.js";

export default {
  name: "AiConfigManagement",
  data() {
    return {
      selectedConfigId: null,
      activeTab: "basic",
      configList: [],
      currentConfig: { id: null, configName: "", taskType: "", description: "", isActive: 1 },
      paramsList: [],
      currentTemplate: { id: null, configId: null, templateName: "", promptContent: "", templateType: "system", templateUsage: "default", variables: "", editing: false },
      templateBackup: {},
      previewValues: {},
      previewResult: {},
      backupData: {},
      
      // 通用对话框配置
      dialogConfig: {
        visible: false,
        title: "",
        form: {},
        fields: [],
        onSubmit: null
      },
      
      // 静态配置数据
      taskTypes: [
        { label: "文章生成", value: "article_generation" },
        { label: "题目生成", value: "question_generation" }
      ],
      
      paramTypes: [
        { label: "字符串", value: "string" },
        { label: "数字", value: "number" },
        { label: "布尔", value: "boolean" },
        { label: "JSON", value: "json" }
      ],
      
      templateTypes: [
        { label: "系统提示词", value: "system" },
        { label: "用户提示词", value: "user" }
      ],
      
      templateUsages: [
        { label: "默认", value: "default" },
        { label: "动态拼接", value: "dynamic" }
      ],
      
      configRules: {
        configName: [{ required: true, message: "请输入配置名称", trigger: "blur" }],
        taskType: [{ required: true, message: "请选择任务类型", trigger: "change" }]
      }
    };
  },
  
  created() {
    this.loadConfigList();
  },
  
  methods: {
    // 基础数据加载
    async loadConfigList() {
      try {
        const response = await getAiTaskConfigList();
        this.configList = response.rows;
      } catch (error) {
        this.$modal.msgError("加载配置列表失败");
      }
    },
    
    async handleConfigChange(configId) {
      if (!configId) return;
      try {
        const response = await getCompleteConfig(configId);
        const data = response.data;
        this.currentConfig = { ...data.config };
        this.paramsList = data.params.map(param => ({ ...param, editing: false }));
        
        // 处理单个模板
        if (data.templates && data.templates.length > 0) {
          this.currentTemplate = { ...data.templates[0], editing: false };
        } else {
          this.currentTemplate = { 
            id: null, 
            configId: this.selectedConfigId, 
            templateName: "", 
            promptContent: "", 
            templateType: "system", 
            templateUsage: "default", 
            variables: "", 
            editing: false 
          };
        }
        
        this.previewValues = {};
        this.previewResult = {};
        this.$message.success("配置加载成功");
      } catch (error) {
        this.$modal.msgError("加载配置详情失败");
      }
    },
    
    // 通用编辑功能
    editItem(type, item, index) {
      this.backupData[`${type}_${index}`] = { ...item };
      this[type + 'List'][index] = { ...item, editing: true };
    },
    
    cancelEdit(type, item, index) {
      if (item.id) {
        this[type + 'List'][index] = { ...this.backupData[`${type}_${index}`], editing: false };
      } else {
        this[type + 'List'].splice(index, 1);
      }
    },
    
    async deleteItem(type, item, index) {
      try {
        await this.$confirm("确定删除吗？", "警告", { type: "warning" });
        if (item.id) {
          const deleteFunc = type === 'params' ? removeConfigParams : removeConfigTemplates;
          await deleteFunc([item.id]);
        }
        this[type + 'List'].splice(index, 1);
        this.$message.success("删除成功");
      } catch (error) {
        if (error !== 'cancel') this.$modal.msgError("删除失败");
      }
    },
    
    // 参数相关
    addParam() {
      this.paramsList.push({
        id: null, 
        configId: this.selectedConfigId, 
        paramKey: "", 
        paramValue: "",
        paramType: "string", 
        paramDescription: "", 
        isRequired: 0,
        sortOrder: this.paramsList.length, 
        editing: true
      });
    },
    
    async saveParam(row, index) {
      if (!row.paramKey) {
        this.$message.warning("参数键名不能为空");
        return;
      }
      try {
        await batchSaveConfig({ configId: this.selectedConfigId, params: [row] });
        await this.handleConfigChange(this.selectedConfigId);
        this.$message.success("保存成功");
      } catch (error) {
        this.$modal.msgError("保存失败");
      }
    },
    
    // 模板相关方法 - 修改为单个模板管理
    createTemplate() {
      this.templateBackup = { ...this.currentTemplate };
      this.currentTemplate = {
        id: null,
        configId: this.selectedConfigId,
        templateName: "",
        promptContent: "",
        templateType: "system",
        templateUsage: "default",
        variables: "",
        editing: true
      };
    },
    
    editTemplate() {
      this.templateBackup = { ...this.currentTemplate };
      this.currentTemplate.editing = true;
    },
    
    cancelTemplateEdit() {
      this.currentTemplate = { ...this.templateBackup, editing: false };
    },
    
    async saveTemplate() {
      if (!this.currentTemplate.templateName || !this.currentTemplate.promptContent) {
        this.$message.warning("模板名称和内容不能为空");
        return;
      }
      try {
        await batchSaveConfig({ 
          configId: this.selectedConfigId, 
          templates: [this.currentTemplate] 
        });
        await this.handleConfigChange(this.selectedConfigId);
        this.$message.success("保存成功");
      } catch (error) {
        this.$modal.msgError("保存失败");
      }
    },
    
    // 文本映射方法
    getParamTypeText(type) {
      const typeMap = {
        string: "字符串",
        number: "数字",
        boolean: "布尔",
        json: "JSON"
      };
      return typeMap[type] || type;
    },
    
    getTemplateTypeText(type) {
      return type === 'system' ? '系统提示词' : '用户提示词';
    },
    
    getTemplateUsageText(usage) {
      return usage === 'default' ? '默认' : '动态拼接';
    },
    
    // 配置管理
    async saveConfig() {
      try {
        await updateAiTaskConfig(this.currentConfig);
        this.$message.success("保存成功");
        this.loadConfigList();
      } catch (error) {
        this.$modal.msgError("保存失败");
      }
    },
    
    handleAddConfig() {
      this.showDialog("新增AI任务配置", {
        configName: "", taskType: "", description: ""
      }, [
        { prop: "configName", label: "配置名称", component: "el-input", props: {} },
        { prop: "taskType", label: "任务类型", component: "el-select", props: { children: this.taskTypes } },
        { prop: "description", label: "配置描述", component: "el-input", props: { type: "textarea", rows: 3 } }
      ], this.submitNewConfig);
    },
    
    copyConfig() {
      this.showDialog("复制配置", {
        configName: this.currentConfig.configName + "_副本"
      }, [
        { prop: "configName", label: "新配置名称", component: "el-input", props: {} }
      ], this.submitCopyConfig);
    },
    
    // 通用对话框
    showDialog(title, form, fields, onSubmit) {
      this.dialogConfig = { 
        visible: true, 
        title, 
        form, 
        fields, 
        onSubmit 
      };
    },
    
    async submitNewConfig() {
      try {
        await addAiTaskConfig(this.dialogConfig.form);
        this.dialogConfig.visible = false;
        this.$message.success("新增成功");
        this.loadConfigList();
      } catch (error) {
        this.$modal.msgError("新增失败");
      }
    },
    
    async submitCopyConfig() {
      try {
        await copyAiConfig(this.selectedConfigId, this.dialogConfig.form);
        this.dialogConfig.visible = false;
        this.$message.success("复制成功");
        this.loadConfigList();
      } catch (error) {
        this.$modal.msgError("复制失败");
      }
    },
    
    // 预览功能
    async previewPrompt() {
      try {
        const response = await previewConfigPrompt(this.selectedConfigId, this.previewValues);
        this.previewResult = response.data;
        this.$message.success("预览生成成功");
      } catch (error) {
        this.$modal.msgError("预览生成失败");
      }
    }
  }
};
</script>

<style scoped>
.app-container { 
  padding: 20px; 
}

.card-header { 
  display: flex; 
  justify-content: space-between; 
  align-items: center; 
}

.mb-4 { 
  margin-bottom: 16px; 
}

.mb-3 { 
  margin-bottom: 12px; 
}

.ml-2 { 
  margin-left: 8px; 
}

.text-red-500 { 
  color: #f56565; 
}

.text-gray-500 {
  color: #6b7280;
}

.text-center {
  text-align: center;
}

.py-8 {
  padding-top: 32px;
  padding-bottom: 32px;
}

.bg-gray-50 { 
  background-color: #f9fafb; 
}

.p-4 { 
  padding: 16px; 
}

.rounded { 
  border-radius: 6px; 
}

.whitespace-pre-wrap { 
  white-space: pre-wrap; 
}

.font-bold { 
  font-weight: bold; 
}

.flex { 
  display: flex; 
}

.justify-between { 
  justify-content: space-between; 
}

.items-center { 
  align-items: center; 
}

.param-value {
  max-width: 200px;
  word-break: break-all;
  white-space: pre-wrap;
}

.ai-big-btn {
  margin: 0 8px 8px 0;
  font-size: 18px;
  height: 48px;
  line-height: 48px;
}
</style>